package com.gxy.learn.backup.runner;

import com.alibaba.fastjson.JSONObject;
import com.gxy.learn.backup.config.ConfigurationPropertiesConfig;
import com.gxy.learn.backup.task.BackupDataDelTask;
import com.gxy.learn.backup.task.BackupDataIndexTask;
import com.gxy.learn.backup.task.BackupDataTask;
import com.gxy.learn.backup.vo.ConfigVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 应用初始化后，去执行一段代码块逻辑，这段初始化代码在整个应用生命周期内只会执行一次。
 */
@Slf4j
@Component
public class ApplicationStartupRunner implements CommandLineRunner {

    @Autowired
    private BackupDataTask backupDataTask;
    @Autowired
    private BackupDataIndexTask backupDataIndexTask;
    @Autowired
    private BackupDataDelTask backupDataDelTask;
    @Autowired
    private ConfigurationPropertiesConfig configurationPropertiesConfig;


    @Override
    public void run(String... args) throws Exception {
        ExecutorService executorService = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
        ConfigVO configVO = null;
        try {
            JSONObject js = new JSONObject();
            js.put("tenantYearMonths", JSONObject.parseObject(configurationPropertiesConfig.getConfigJsonStr()));
            configVO = JSONObject.toJavaObject(js, ConfigVO.class);
        } catch (Exception e) {
            log.error("配置信息错误！", e);
            return;
        }
        if (null == configVO) {
            log.error("配置信息错误！");
            return;
        }
        ConfigVO finalConfigVO = configVO;
//        executorService.execute(new Runnable() {
//            @Override
//            public void run() {
//                backupDataDelTask.doConsumptionTaskByYearAndMonth(finalConfigVO);
//            }
//        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                backupDataTask.doConsumptionTaskByYearAndMonth(finalConfigVO);
            }
        });
//        executorService.execute(new Runnable() {
//            @Override
//            public void run() {
//                backupDataIndexTask.doConsumptionTaskByYearAndMonth(finalConfigVO);
//            }
//        });
    }
}
